var express = require('express');
var router = express.Router();
var MongoClient = require("mongodb").MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/school';
var $ = require('jquery')(require("jsdom").jsdom().defaultView);
var async = require('async');
var fs=require('fs');

// 用于储存电影数据的数组
var movies = [];

/* GET home page. */
router.get('/', function(req, res, next) {

	/*MongoClient.connect(DB_CONN_STR,function(error, db){
		if (error) {
			console.log(error);
			return;
		}
		var conn = db.collection("movies");

		conn.find().toArray(function(error, result){
			if (error) {
				console.log(error);
				return;
			}	


		//在数据库中取出自己需要的类容以对象的形式放入到数组中保存
			for(var i = 0; i < result.length; i++){

				var obj = {}, //用对象形式存放的 movies 数组中
					empty = []; //零时数组，放置演员数组，然后添加到对象中

				obj.title = result[i].title;
				obj.year = result[i].year;
				obj.images = result[i].images.large;
				obj.genres = result[i].genres;

				for(var j = 0; j < result[i].casts.length; j++){
					var casts = result[i].casts[j].name;
					empty.push(casts);
				}
				obj.casts = empty;
				// console.log(obj)

				movies.push(obj);
			}


			res.render("index",{movies: movies});
			db.close();
		});
	});*/

 		$(function(){
 			$.ajax({
		         type : "get", //jquey是不支持post方式跨域的
		         url : "http://api.douban.com/v2/movie/top250", //跨域请求的URL
		         dataType : "jsonp",
		         success : function(data){ 

		         	var result = data.subjects;
			        for(var i = 0; i < result.length; i++){

						var obj = {}, //用对象形式存放的 movies 数组中
							empty = []; //零时数组，放置演员数组，然后添加到对象中

						obj.title = result[i].title;
						obj.year = result[i].year;
						obj.images = result[i].images.large;
						obj.genres = result[i].genres;

						for(var j = 0; j < result[i].casts.length; j++){
							var casts = result[i].casts[j].name;
							empty.push(casts);
						}
						obj.casts = empty;

						movies.push(obj);
					}
					
					res.render("index",{movies: movies,username:req.session.username});
					db.close();

				}
	 		});
 		});


	
});

//登录
router.get('/login',function(req,res){

	res.render('login',{});
})

//注册
router.get('/register',function(req,res){

	res.render('register',{});
})

// 详情页面  点击某一步电影是的接口
router.get('/detail',function(req,res){
	/*res.send('register page');*/
	/*res.render('detail',{ab:'试验品'});*/
	//初始化页码参数
	/*var pageNo=req.body.pageNo,
		pageNo=pageNo?pageNo:1,
		pageSize=5,
		count=0
		totalPages=0;
	var findDate=function(db,callback){
	    var conn = db.collection('comment');
	    //并行无关联
	    async.parallel([
	    	function(callback){
	    		conn.find({}).toArray(function(error,results){
	    			if(error){
	    				return;
	    			}else{
	    				totalPages=Math.ceil(results.length/pageSize);
	    				count=results.length;
	    				callback(null,'');
	    			}
	    		})
	    	},
	    	function(callback){
	    		conn.find({}).sort({time:-1}).skip((pageNo-1)*pageSize).limit(pageSize).toArray(function(error,results){
	    			if (error) {
	    				return;
	    			}
			      res.render('detail', {comments: results});
			    });

	    	}
	    ],function(error,results){
	    	callback(results[1]);
	    })
	 };
	MongoClient.connect(DB_CONN_STR,function(error,db){
		if (error) {
			return;
		}else{
			findDate(db,function(results){
				var data={
					pageSize:pageSize,
					pageNo:pageNo,
					totalPages:totalPages,
					comments:results,
					username:req.session.username
				};
				console.log(data+'lalalallal');
				res.render('detail',data)
			});
		};

	});*/


	//初始化参数
		var pageNo = req.query.pageNo,
			pageNo = pageNo?pageNo:1,
			pageSize = 2,
			count = 0,
			totalPages = 0;
		var queryData = function(db,callback){
					//连接表
					var conn = db.collection('comment');
					//并行无关联
					async.parallel([
						function(callback){
							conn.find({}).toArray(function(err,results){
								if(err){
									return;
								}else{
									totalPages = Math.ceil(results.length/pageSize);
									count = results.length;

									// 第一个数组内容，我们返回的是空，并没有将count/totalPages当成回调返回，原因是什么呢？
									// 因为我们已经把total/totalPages设置成了js的全局变量，我在下面可以单独的去启用它们
									callback(null,'');
								}
							})
						},
						function(callback){
							conn.find({}).sort({_id:-1}).skip( (pageNo-1)*pageSize ).limit(pageSize).toArray(function(err,results){
								if(err){
									return;
								}
								callback(null,results);
							});

						}
					],function(err,results){
						callback(results[1]);
					})

				}

	MongoClient.connect(DB_CONN_STR,function(err,db){
		if(err){
				return;
		}else{
	    	queryData(db,function(results){
						var data = {
							pageNo:pageNo,
							totalPages:totalPages,
							comments:results,
							count:count
						}
						// console.log(data)
			res.render('detail', data);
				});
    	}
    });

});


router.get('/logout',function(req,res){
	// 方法一
	// req.session.email = undefined;
	// 方法二
	req.session.destroy(function(err){
		res.redirect('/');
	})
	

});

module.exports = router;
